//
//  IMAtUtil.swift
//  swiftim
//
//  Created by yangjian on 2023/7/17.
//

import Foundation


extension NSAttributedString.Key {
    public static let messageAt: NSAttributedString.Key = NSAttributedString.Key.init(rawValue: "msg_at")
}
let chatBarTextAttributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font:chatBar_textFont,
                      NSAttributedString.Key.foregroundColor:UIColor.orange]

class IMChatBarMsgAtUtil {
    static func fetchAtUsers(atHelper : IMChatBarMsgAtHelper,attributedText : NSAttributedString){
//        guard let attributedText = self.textView.attributedText else {
//            print("没有被@的人")
//            atHelper.atters.removeAll()
//            return
//        }
        atHelper.validateAtter(attributedText: attributedText)
        for atter in atHelper.atters {
            print("- userName:\(atter.username),nickName:\(atter.display),atid:\(atter.atid),range:\(atter.range)")
        }
    }

    static func selectAt(atHelper : IMChatBarMsgAtHelper,textView : UITextView,range: NSRange ){
        guard let chattingController = IMChatVCManager.share.currentChatVC else {return}
        guard let conversation = chattingController.conversation else {return}
        if conversation.type != EMConversationType.groupChat {
            return
        }
        let atController = JJGroupChatSelectAtController.init(groupid: conversation.conversationId) { model in
            let mutableAttributedString = NSMutableAttributedString.init(attributedString: textView.attributedText)
            let atRange = NSMakeRange(range.location, 1)
            if mutableAttributedString.attributedSubstring(from: atRange).string != "@" {
                return
            }
            let atter = IMChatBarMsgAtter.init()
            atter.atAll = model.atAll
            atter.username = model.username
            atter.display = "@\(model.nickName)"
            atter.atid = atHelper.fetchAtid()
            atHelper.atters.append(atter)
            
            var atAttributes = chatBarTextAttributes
            atAttributes[NSAttributedString.Key.messageAt] = "\(atter.atid)"
            let atAttributedString =
            NSAttributedString.init(string: "\(atter.display) ", attributes: atAttributes)
            mutableAttributedString.replaceCharacters(in: atRange, with: atAttributedString)
            let offset = textView.contentOffset;
            textView.attributedText = mutableAttributedString
            textView.selectedRange = NSMakeRange(range.location + atAttributedString.length, 0)
            textView .setContentOffset(offset, animated: false)
            
        }
        chattingController.present(atController, animated: true) {
        }
    }
    
    static func generateAtMessage(atHelper : IMChatBarMsgAtHelper,attributedText : NSAttributedString,conversationID : String,chatType : EMChatType) -> EMChatMessage {
        let sendText = attributedText.string
        if sendText.count == 0 {
            print("没有要发送的信息!!!")
        }
        let body = EMTextMessageBody.init(text: sendText)
        IMChatBarMsgAtUtil.fetchAtUsers(atHelper: atHelper,attributedText: attributedText)
        var atlist = [Any].init()
        var oldAtList = [String].init()
        var atAll = false
        for atter in atHelper.atters {
            if atter.atAll {
                atAll = true
            }else {
                var at = [String:String].init()
                at["username"] = atter.username;
                at["display"] = atter.display;
                at["range"] = "\(atter.range.location):\(atter.range.length)"
                atlist.append(at)
                oldAtList.append(atter.username);
            }
        }
        var messageExt = [String : Any].init()
        messageExt[message_atter_list] = oldAtList
        messageExt[message_atter_atAll] = atAll ? "1" : "0"
        messageExt[message_atter_list_hasRange] = atlist
        let message = EMChatMessage.init(conversationID: conversationID, body: body, ext: messageExt)
        message.chatType = chatType
        return message
    }
    
}


class IMChatBarMsgAtter {
    var atid : Int = 0
    var atAll = false
    var username = ""
    var display = ""//携带@
    var range = NSMakeRange(0, 0)
}

class IMChatBarMsgAtHelper{
    private var atid : Int = 0
    func fetchAtid() -> Int {
        atid += 1
        return atid
    }
    func recoverAtid() {
        atid = 0
    }
    var atters = [IMChatBarMsgAtter].init()
    func validateSubAtter(atter:IMChatBarMsgAtter,subAttributedString:NSAttributedString) -> Bool {
        for i in 0 ..< subAttributedString.length {
            let aAttributedString = subAttributedString.attributedSubstring(from: NSMakeRange(i, 1))
            let kv = aAttributedString.attributes(at: 0, effectiveRange: nil)
            guard let atid = kv[NSAttributedString.Key.messageAt] else {return false}
//            print("id对比(\(atid))(\(atter.atid))")
            if (atid as! String) != "\(atter.atid)" {
                return false
            }
        }
        return true
    }
    func validateAtter(attributedText : NSAttributedString){
        let resultAtters = atters.filter { atter in
            if !attributedText.string.contains(atter.display) {
                return false
            }
            let ranges = nsranges(string: attributedText.string, subString: atter.display)
            for i in 0 ..< ranges.count {
                if validateSubAtter(atter: atter,
                                    subAttributedString: attributedText.attributedSubstring(from: ranges[i])) {
                    atter.range = ranges[i];
                    print("正确的")
                    return true
                }
            }
            print("错误的")
            return false
        }
        self.atters = resultAtters
    }
}
